var iot = require('iot');
var network = require('network');

var net = network.openNetWorkClient();

var productKey = 'your productKey';      /* your productKey */
var deviceName = 'your deviceName';      /* your deviceName */
var deviceSecret = 'your deviceSecret';  /* your deviceSecret */

var device;

function createDevice() {
        device = iot.device({
        productKey: productKey,
        deviceName: deviceName,
        deviceSecret: deviceSecret,
        region: 'cn-shanghai',
        success: function () {
            console.log('iot: [success] connect');
            onConnect();
        },
        fail: function () {
            console.log('iot: [failed] connect');
        }
    });

    device.on('connect', function () {
        console.log('iot: [success] iot.on(\'connect\')');
    });
    
    /* 网络断开事件 */
    device.on('disconnect', function () {
        console.log('iot: [success] iot.on(\'disconnect\')');
    });
    
    /* 关闭连接事件 */
    device.on('close', function () {
        console.log('iot: [success] iot.on(\'close\')');
    });
    
    /* 发生错误事件 */
    device.on('error', function (err) {
        throw new Error('iot: [failed] iot.on(\'error\') ' + err);
    });
    
    /* 云端设置属性事件 */
    device.on('props', function (payload) {
        console.log('iot: [success] iot.on(\'props\'), payload: ' + JSON.stringify(payload));
    });
    
    /* 云端下发服务事件 */
    device.on('service', function (id, payload) {
        console.log('iot: [success] iot.on(\'service\'), id: ' + id + ', payload: ' + JSON.stringify(payload));
    });
}


var lightSwitch = 0;
function onConnect() {
    /** post properties */
    lightSwitch = 1 - lightSwitch;
    device.postProps({
        payload: {
            LightSwitch: lightSwitch
        },
        success: function () {
            console.log('iot: [success] iot.postProps');
        },
        fail: function () {
            console.log('iot: [failed] iot.postProps');
        }
    });
    /** post events */
    device.postEvent({
        id: 'Error',
        params: {
            ErrorCode: 0
        },
        success: function () {
            console.log('iot: [success] iot.postEvent');

        },
        fail: function () {
            console.log('iot: [failed] iot.postEvent');
        }
    });
}

var status = net.getStatus();
console.log('net status is: ' + status);

if (status == 'connect') {
    createDevice();
} else {
    net.on('connect', function () {
        createDevice();
    });
}